<?php
/**
 * 货币（币种汇率）（基础）
 * (model)
 */

namespace App\Models\Basics;

use Illuminate\Database\Eloquent\Model;
class ExchangeRate extends Model
{
    protected $table = 'b_exchange_rate';

    public $timestamps = false;

    protected $guarded  = [];

    public function currency()
    {
        return $this->belongsTo(Currency::class,'currency_code','code');
    }

    public static function getRateOddsToRMB($code,$at){
        if(!$code)return 1;
        $date = date('Y-m-01',$at);
        $rateOdds = self::query()
            ->where('currency_code',$code)
            ->where('effective_at',$date)
            ->value('rate_odds');
        if(!$rateOdds){
            $re = self::query()
                ->where('currency_code',$code)
                ->orderBy('effective_at','DESC')
                ->first();
            return $re->rate_odds ?? 1;
        }else{
            return $rateOdds;
        }
    }
}
